package com.itheima.reggie.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class CheckLoginFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    public void destroy() {
    }
    public void init(FilterConfig config) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1.资源放行
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //获取请求路径
        String uri = request.getRequestURI();
        String[] urls={
                "/user/login",
                "/user/sendMsg",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };
        boolean check = check(urls, uri);
        if(check){
            chain.doFilter(request, response);
            return;
        }
        //判断是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if(empId!=null||loginUser!=null){
            log.info("已登录");
           // Long empId = (Long) request.getSession().getAttribute("employee");S
//            BaseContext.setCurrentId(empId);
//           BaseContext.setCurrentId(loginUserPhone);
            if(empId!=null){
                BaseContext.setCurrentId(empId);
            }
            if(loginUser!=null){
                BaseContext.setCurrentId(loginUser.getId());
            }
            chain.doFilter(request, response);
            BaseContext.release();
            return;
        }
        log.info("未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
